﻿namespace SuperMarieApi.App.Controllers.Framework.DataAccess
{
    using System;
    using System.Data;
    using System.Data.Common;

    using SuperMarieApi.App.Controllers.Framework.Common;

    public class DbHelper
    {
        private DbProviderFactory _dbProviderFactory;
        private string _connectionString;

        public DbHelper(string providerName, string connectionString)
        {
            if (StringHelper.IsNullOrEmpty(providerName))
            {
                throw new ArgumentException("providerName cannot be null or empty.");
            }

            if (StringHelper.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("connectionString cannot be null or empty.");
            }

            this._dbProviderFactory = DbProviderFactories.GetFactory(providerName);
            this._connectionString = connectionString;
        }

        public DbCommand CreateDbCommand(string commandText, CommandType commandType, int commandTimeout)
        {
            var conn = this._dbProviderFactory.CreateConnection();
            conn.ConnectionString = this._connectionString;
            var cmd = this._dbProviderFactory.CreateCommand();
            cmd.CommandText = commandText;
            cmd.CommandTimeout = commandTimeout;
            cmd.CommandType = commandType;
            cmd.Connection = conn;

            return cmd;
        }

        public void CreateParameter(DbCommand cmd, string name, DbType dbType, int size, ParameterDirection direction)
        {
            var param = cmd.CreateParameter();
            param.ParameterName = name;
            param.DbType = dbType;
            if (size > 0)
            {
                param.Size = size;
            }
            param.Direction = direction;

            cmd.Parameters.Add(param);
        }

        public DbDataAdapter CreateDataAdapter()
        {
            return this._dbProviderFactory.CreateDataAdapter();
        }
    }
}
